package com.wyt.controller;

import com.wyt.dao.MenuMapper;
import com.wyt.entity.Employee;
import com.wyt.entity.Menu;
import com.wyt.until.CommonResult;
import com.wyt.until.MenuList;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.List;

/**
 * @program: xiangmu01
 * @description: 左边菜单栏
 * @author: 王一同
 * @create: 2021-11-21 16:49
 **/
@RestController
public class LeftController {
    @Autowired
    private MenuMapper menuMapper;

    @RequestMapping("getMenuByRoleid")
    public CommonResult findMenuByRoleid(HttpSession session){
        Employee login = (Employee) session.getAttribute("login");
        Integer integer = login.geteRole();
        List<MenuList> menuByRoleId = menuMapper.findMenuByRoleId(integer);
        //为菜单分层
        //1.找到所有的一级菜单。特点 父亲ID=0
        List<MenuList> friends = new ArrayList<MenuList>();
        for (MenuList menu: menuByRoleId){
            if(menu.getMpid()==0){
                friends.add(menu);
            }
        }
        //找二级菜单
        for (MenuList first:friends) {
            first.setChildren(foundChildren(menuByRoleId,first.getMid()));
        }
        return new CommonResult(200,"查询成功",friends);
    }

    /**
     *
     * @param menus 所有的菜单
     * @param pid 父亲ID
     * @return
     */

    public List<MenuList> foundChildren(List<MenuList> menus,Integer pid){
        List<MenuList> menuLists = new ArrayList<MenuList>();
        for (MenuList m: menus) {
            if(m.getMpid().equals(pid)){
                menuLists.add(m);
            }
        }
        for(MenuList c:menuLists){
            foundChildren(menus,c.getMid());
        }
        return  menuLists;
    }

}
